import {
  FC,
  ReactElement,
  useState,
  useCallback,
  useMemo,
  useEffect,
} from "react";
import styled from "styled-components";
import { FlexDiv, ThemeFlexDiv } from "../BUI";
import { ThemeBgc, ThemeText } from "../BUI/View/ThemeView";
import PaimonArrowIcon from "../PaimonArrowIcon";

interface IProps {}

enum TagField {
  title = "title",
  connector = "connector",
  tail = "tail",
  color = "color",
}

interface TagProps {
  [TagField.title]: string;
  [TagField.connector]: string;
  [TagField.tail]: string;
  [TagField.color]: Omit<TagProps, "color">;
}

const MyTags: TagProps[] = [
  {
    [TagField.title]: "程序猿",
    [TagField.connector]: "&",
    [TagField.tail]: "二次猿",
    [TagField.color]: {
      [TagField.title]: "#0f0",
      [TagField.connector]: "#f00",
      [TagField.tail]: "#faa",
    },
  },
  {
    [TagField.title]: "喜欢的游戏",
    [TagField.connector]: ":",
    [TagField.tail]: "原神",
    [TagField.color]: {
      [TagField.title]: "#f0f",
      [TagField.connector]: "#0a0",
      [TagField.tail]: "#afa",
    },
  },
  {
    [TagField.title]: "喜欢的框架",
    [TagField.connector]: ":",
    [TagField.tail]: "react",
    [TagField.color]: {
      [TagField.title]: "#51f",
      [TagField.connector]: "#0f0",
      [TagField.tail]: "#00f",
    },
  },
  {
    [TagField.title]: "喜欢的运动",
    [TagField.connector]: ":",
    [TagField.tail]: "玩原神",
    [TagField.color]: {
      [TagField.title]: "#faf",
      [TagField.connector]: "#f1f",
      [TagField.tail]: "#afa",
    },
  },
];

const KnowMe: FC<IProps> = (): ReactElement => {
  const [currIndex, setCurrIndex] = useState(2);
  const tagLength = useMemo(() => MyTags.length, []);

  const nextTag = useCallback(() => {
    setCurrIndex(index => (index + 1 > tagLength + 1 ? 2 : index + 1));
  }, [tagLength]);

  const prevTag = useCallback(() => {
    setCurrIndex(index => (index - 1 < 2 ? tagLength + 1 : index - 1));
  }, [tagLength]);

  useEffect(() => {
    const canvasWidth = 400;
    const canvasHeight = 400;
    const canvas = document.getElementById("textOutput") as HTMLCanvasElement;
    canvas.width = canvasWidth;
    canvas.height = canvasHeight;
    const ctx = canvas.getContext("2d") as CanvasRenderingContext2D;

    ctx.clearRect(0, 0, canvasWidth, canvasHeight);

    const str =
      "HELLO 我是宏斌一名大前端开发工程狮\n出生年月日: 2000/08/20\n星座: 狮子座\n学历: 本科\n毕业年份: 2023\n专业: 计算机科学与技术\n喜欢学习并尝试新技术\n有网页 小程序 App 后端 开发经验\n喜欢交流，互相学习\n与其他开发人员交流总让我感到愉悦\n对前端发展感到振奋^.^";
    const startSpot: number[] = [10, 10]; //开始点
    const currentSpot = [...startSpot]; //记录当前的坐标
    const fontSize = 20; //字体
    const mediumFontSize = 15; //字体
    const smallFontSize = 12; //字体
    const lingHeight = 10; //行间距

    const drawText: any = (text: string, x: number, y: number) => {
      ctx.beginPath();
      ctx.font = `${fontSize}px Arial Rounded MT Bold, Helvetica Rounded, Arial, sans-serif`;
      ctx.fillStyle = "#" + Math.round(Math.random() * 0xffffff).toString(16);
      ctx.textBaseline = "top";
      ctx.fillText(text, x, y);
      ctx.closePath();
    };

    const drawVerticalLine = (x: number, start: number, end: number) => {
      ctx.beginPath();
      ctx.moveTo(x, start);
      ctx.lineTo(x, end);
      ctx.strokeStyle = "#000";
      ctx.stroke();
      ctx.closePath();
    };

    let index = 0; //画到第几个字符了
    const space = 100;

    //换行
    const lineFeed = () => {
      currentSpot[1] += fontSize + lingHeight;
      currentSpot[0] = startSpot[0];
    };

    function draw() {
      const char = str[index++];
      //清除上一条插入点
      ctx.clearRect(currentSpot[0] + 9, currentSpot[1], 2, fontSize);
      if (!char) return;
      // console.log(char);
      if (char == "\n") lineFeed();
      else {
        if (currentSpot[0] > canvasWidth - fontSize) lineFeed();
        //如果是字母或斜线 空格 间距要小点
        let size = fontSize;
        const smallChar = /[A-Za-z0-9/ ]/.test(char);
        if (smallChar)
          size = /[A-Z0-9]/.test(char) ? mediumFontSize : smallFontSize;
        drawText(char, ...currentSpot); //画一个文字
        currentSpot[0] += size; //绘画点向右移动
        drawVerticalLine(
          currentSpot[0] + 10,
          currentSpot[1],
          currentSpot[1] + fontSize
        );
      }
      setTimeout(() => draw(), space);
    }

    setTimeout(() => draw(), space);
  }, []);

  return (
    <Container>
      <div>
        <canvas id="textOutput"></canvas>
      </div>
      <TagsContainer currIndex={currIndex} items="center">
        <PaimonArrowIcon onClick={prevTag} left="10px" dir="left" />
        {MyTags.map(tag => (
          <MyTag key={tag[TagField.title]} tag={tag} />
        ))}
        <PaimonArrowIcon onClick={nextTag} right="10px" dir="right" />
      </TagsContainer>
    </Container>
  );
};

export default KnowMe;

interface MyTagProps {
  tag: TagProps;
}

const MyTag: FC<MyTagProps> = ({
  tag: { color, ...content },
}): ReactElement => {
  return (
    <TagItem items="center" justify="center">
      <h2 style={{ color: color[TagField.title] }}>
        {content[TagField.title]}
      </h2>
      <h2 style={{ color: color[TagField.connector] }}>
        &nbsp;{content[TagField.connector]}&nbsp;
      </h2>
      <h2 style={{ color: color[TagField.tail] }}>{content[TagField.tail]}</h2>
    </TagItem>
  );
};

const TagItem = styled(FlexDiv).attrs({ "data-tag-item": "" })`
  width: 100%;
  flex-shrink: 0;
  position: absolute;
  transition-property: opacity, left;
  transition-duration: 0.3s;
  transition-timing-function: ease-in;
`;

const TagsContainer = styled(ThemeFlexDiv)<{ currIndex: number }>`
  position: relative;

  & > div[data-tag-item]:nth-child(odd) {
    left: 100%;
  }
  & > div[data-tag-item]:nth-child(even) {
    left: -100%;
  }
  & > div[data-tag-item]:nth-child(${props => props.currIndex}) {
    opacity: 1;
    left: 0;
  }

  & > div {
    opacity: 0;
  }

  &:hover {
    div[data-arrow] {
      opacity: 1;
    }
  }
`;

const Container = styled.div`
  width: 25rem;
  height: 30rem;
  border-radius: 10px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  box-shadow: ${props =>
    props.theme.mode === "dark" ? "" : "3px 3px 17px 0px #435873"};

  & > div {
    position: relative;
    ${ThemeBgc};
  }

  & > div:first-child {
    flex: 4;
  }

  & > div:last-child {
    flex: 1;
  }
  & > div:last-child::before {
    content: "Hong Bin";
    background-color: ${props => props.theme.bg};
    padding: 2px 30px;
    position: absolute;
    border-radius: 5px;
    box-shadow: 0 2px 10px 1px
      ${props => (props.theme.mode === "dark" ? "#333" : "#eee")};
    top: 0;
    left: 50%;
    font-size: 1.2rem;
    letter-spacing: 1px;
    transform: translate(-50%, -50%);
    /* -webkit-text-fill-color: transparent;
    -webkit-text-stroke: 1px ${props => props.theme.text}; */
    text-shadow: 1px 1px 2px #222222;
    ${ThemeText};
  }
`;
